package server.ui;

import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import server.session.OnlineUser;
import server.session.SessionManager;

import java.util.List;

public class OnlineUserController {

    @FXML private TableView<OnlineUser> table;
    @FXML private TableColumn<OnlineUser, Integer> idColumn;
    @FXML private TableColumn<OnlineUser, String> nameColumn;
    @FXML private TableColumn<OnlineUser, String> ipColumn;
    @FXML private TableColumn<OnlineUser, String> timeColumn;
    @FXML private TableColumn<OnlineUser, Void> actionColumn;

    private final ObservableList<OnlineUser> onlineUsers = FXCollections.observableArrayList();

    @FXML
    public void initialize() {
        // 初始化表格列
        setupTableColumns();

        // 设置表格样式
        setupTableStyle();

        // 添加操作按钮
        addActionButtonsToTable();

        // 初始刷新数据
        refreshOnlineUsers();
    }

    private void setupTableColumns() {
        idColumn.setCellValueFactory(new PropertyValueFactory<>("clientId"));
        nameColumn.setCellValueFactory(new PropertyValueFactory<>("username"));
        ipColumn.setCellValueFactory(new PropertyValueFactory<>("ip"));
        timeColumn.setCellValueFactory(new PropertyValueFactory<>("lastActiveTime"));

        // 设置列样式
        idColumn.setStyle("-fx-alignment: CENTER;");
        nameColumn.setStyle("-fx-alignment: CENTER_LEFT;");
        ipColumn.setStyle("-fx-alignment: CENTER;");
        timeColumn.setStyle("-fx-alignment: CENTER;");
        actionColumn.setStyle("-fx-alignment: CENTER;");
    }

    private void setupTableStyle() {
        // 设置行高和交替行颜色
        table.setRowFactory(tv -> {
            TableRow<OnlineUser> row = new TableRow<>();
            row.setStyle("-fx-cell-size: 35px;");

            // 交替行颜色
            row.itemProperty().addListener((obs, oldVal, newVal) -> {
                if (newVal != null) {
                    if (row.getIndex() % 2 == 0) {
                        row.setStyle("-fx-background-color: #f9f9f9; -fx-cell-size: 35px;");
                    } else {
                        row.setStyle("-fx-background-color: white; -fx-cell-size: 35px;");
                    }
                }
            });
            return row;
        });
    }

    private void addActionButtonsToTable() {
        actionColumn.setCellFactory(col -> new TableCell<>() {
            private final Button kickButton = new Button("踢下线");
            private final Button muteButton = new Button("禁言");
            private final HBox buttonBox = new HBox(5, kickButton);

            {
                // 设置按钮样式
                kickButton.setStyle("-fx-background-color: #d9534f; -fx-text-fill: white; -fx-font-size: 12px;");
                muteButton.setStyle("-fx-background-color: #4e5bf0; -fx-text-fill: white; -fx-font-size: 12px;");

                // 踢下线按钮事件
                kickButton.setOnAction(e -> handleKickAction());

//                // 禁言按钮事件
//                muteButton.setOnAction(e -> handleMuteAction());
            }

            private void handleKickAction() {
                OnlineUser user = getTableView().getItems().get(getIndex());
                boolean result = SessionManager.kickUser(user.getClientId());
                if (result) {
                    showAlert(Alert.AlertType.INFORMATION, "操作成功", "已踢下线: " + user.getUsername());
                    refreshOnlineUsers();
                } else {
                    showAlert(Alert.AlertType.ERROR, "操作失败", "踢下线失败");
                }
            }

            private void handleMuteAction() {
                OnlineUser user = getTableView().getItems().get(getIndex());
                boolean isMuted = SessionManager.toggleMuteUser(user.getClientId());
                String message = isMuted ? "已禁言: " + user.getUsername() : "禁言: " + user.getUsername();
                showAlert(Alert.AlertType.INFORMATION, "操作成功", message);
                refreshOnlineUsers();
            }

            @Override
            protected void updateItem(Void item, boolean empty) {
                super.updateItem(item, empty);
                if (empty) {
                    setGraphic(null);
                } else {
                    setGraphic(buttonBox);
                }
            }
        });
    }

    private void showAlert(Alert.AlertType type, String title, String message) {
        Alert alert = new Alert(type);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.show();
    }

    @FXML
    public void refreshOnlineUsers() {
        List<OnlineUser> users = SessionManager.listOnlineUsers();
        Platform.runLater(() -> {
            onlineUsers.setAll(users);
            table.setItems(onlineUsers);
            table.refresh();
        });
    }
}